package com.ruikong.dazhi.service.impl.base;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ruikong.dazhi.controller.result.BaseResult;
import com.ruikong.dazhi.controller.result.ResultApi;
import com.ruikong.dazhi.dao.base.PersonnelMapper;
import com.ruikong.dazhi.dao.base.RoleMapper;
import com.ruikong.dazhi.entity.base.Personnel;
import com.ruikong.dazhi.entity.base.Role;
import com.ruikong.dazhi.model.input.UserSearchPageInput;
import com.ruikong.dazhi.model.output.PersonnelOutput;
import com.ruikong.dazhi.service.base.IPersonnelService;
import com.ruikong.dazhi.utils.PageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: cpisystem
 * @description:
 * @author: tybengine
 * @create: 2020-11-11 13:17
 **/
@Service
public class PersonnelServiceImpl implements IPersonnelService {

    @Autowired
    private PersonnelMapper personnelMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final Integer USE_YES = 1;
    private static final Integer USE_NO = 0;

    /**
     * 添加人员账号
     * @return
     */
    public int addPersonAccount(BaseResult result, Personnel personnel) throws UnsupportedEncodingException {
        Personnel per = personnelMapper.getPersonnelByAccount(personnel.getAccount());
        if(per != null){
            result.setMsg("账号已经存在");
            return 0;
        } else {
//            TUser tUser = tUserMapper.getUserById(personnel.getUserId());
//            personnel.setPersonnelName(tUser!=null?tUser.getFname():"");
//            personnel.setPersonnelNumber(tUser!=null?tUser.getFnumber():"");
            personnel.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes("utf-8")));
            personnel.setIsUsed(1);
            int effect =  personnelMapper.addPersonAccount(personnel);
            if(effect > 0){
                return effect;
            }
            result.setMsg("添加失败");
            return 0;
        }
    }

    /**
     * 获取账号
     *
     * @param input
     * @return
     */
    public PageInfo<PersonnelOutput> getPersonnelListPage(UserSearchPageInput input){
        List<Personnel> personals= personnelMapper.getPersonnelList(input.getName(), input.getNumber(), input.getRole());
        List<PersonnelOutput> outputPersonnels = new ArrayList<>();
        for (Personnel item : personals) {
            PersonnelOutput personnelOutput = new PersonnelOutput();
            if(item.getRoleId()!=0){
                Role role = roleMapper.getByRoleId(item.getRoleId());
                personnelOutput.setRoleName(role!=null?role.getRoleName():"");
            }

            personnelOutput.setPersonnelId(item.getPersonnelId());
            personnelOutput.setDeleted(item.isDeleted());
            personnelOutput.setCreateTime(item.getCreateTime());
            personnelOutput.setUpdateTime(item.getUpdateTime());
            personnelOutput.setPersonnelName(item.getPersonnelName());
            personnelOutput.setPersonnelNumber(item.getPersonnelNumber());
            personnelOutput.setAccount(item.getAccount());
            personnelOutput.setRoleId(item.getRoleId());
            personnelOutput.setIsUsed(item.getIsUsed());
            outputPersonnels.add(personnelOutput);
        }

        //利用工具类进行数据拆分
        PageModel pm = new PageModel(outputPersonnels, input.getPageSize());
        List list = pm.getObjects(input.getPageNumber());
        if(list != null){
            //将分页数据转到pageInfo
            PageInfo<PersonnelOutput> pageInfo = new PageInfo<>(list);
            //当前页码数
            pageInfo.setPageNum(pm.getPage());
            //每页数据条数
            pageInfo.setPageSize(pm.getPageRecorders());
            //数据总条数
            pageInfo.setTotal(pm.getTotalRows());
            //是否有下一页
            pageInfo.setHasNextPage(pm.isHasNextPage());
            return pageInfo;
        }
        //所有分页属性都可以从pageInfoDemo拿到；
        return new PageInfo<PersonnelOutput>();
    }

    /**
     * 查询所有的人员列表
     * @return
     */
    public List<Personnel> getPersonnelList(){
        return personnelMapper.getPersonnelList("", "", -1);
    }

    /**
    * 删除账号
    */
    public int deleteAccount(Personnel personnel){
        Personnel getPersonnel = personnelMapper.getByPersonnelId(personnel.getPersonnelId());
        if(getPersonnel==null){
            return 0;
        }
        int effectLine = personnelMapper.deleteAccount(personnel);
        if(effectLine > 0){
            return effectLine;
        }
        return 0;
    }

    @Override
    public int updateAccount(Personnel personnel) {
//        TUser tUser = tUserMapper.getUserById(personnel.getUserId());
//        personnel.setPersonnelName(tUser!=null?tUser.getFname():"");
//        personnel.setPersonnelNumber(tUser!=null?tUser.getFnumber():"");
        return personnelMapper.updPersonAccount(personnel);
    }

    /**
    * 修改密码
    */
    public int updatePassword(JSONObject jsonObject, BaseResult result, HttpSession httpSession) throws UnsupportedEncodingException {
        Personnel user;//操作人
        if( httpSession.getAttribute("personnel")==null){
            result.setMsg(ResultApi.updateFailMsg);
            return 0;
        }else{
            user=(Personnel) httpSession.getAttribute("personnel");
        }

        String oldPassword = jsonObject.get("oldPassword").toString();
        String newPassword = jsonObject.get("newPassword").toString();
        String personnelId = jsonObject.get("personnelId").toString();//需要更改密码的记录Id

        //被修改人
        Personnel personnel = personnelMapper.getByPersonnelId(Integer.parseInt(personnelId));
        if(personnel.getRoleId()==1&&user.getRoleId()!=1){//操作人想要修改超级管理员账号，该情况不允许
            result.setMsg("没有权限，不可操作");
            return 0;
        }

        if(personnel.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes("utf-8")))){
            personnel.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes("utf-8")));
            int effectLine = personnelMapper.updatePassword(personnel);
            if (effectLine > 0) {
                result.setMsg(ResultApi.updateSuccessMsg);
                return effectLine;
            } else {
                result.setMsg(ResultApi.updateFailMsg);
                return 0;
            }
        }else{
            result.setMsg("原密码不正确");
            return 0;
        }
    }

    @Override
    public int resetPassword(Personnel personnel,BaseResult result, HttpSession httpSession)  throws UnsupportedEncodingException {
        Personnel user;//操作人
        if( httpSession.getAttribute("personnel")==null){
            result.setMsg(ResultApi.updateFailMsg);
            return 0;
        }else{
            user=(Personnel) httpSession.getAttribute("personnel");
        }
        if(personnel.getRoleId()==1&&user.getRoleId()!=1){//操作人想要修改超级管理员账号，该情况不允许
            result.setMsg("没有权限，不可操作");
            return 0;
        }
        personnel.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes("utf-8")));
        int effectLine = personnelMapper.updatePassword(personnel);
        if (effectLine > 0) {
            result.setMsg(ResultApi.updateSuccessMsg);
            return effectLine;
        } else {
            result.setMsg(ResultApi.updateFailMsg);
            return 0;
        }
    }

    /**
     * 启用帐号
     */
    @Transactional
    public int invokePersonnel(Personnel personnel){
       // int effect = personnelMapper.invokePersonnel(personnel.getPersonnelId(),personnel.getIsUsed());

          int effect=  personnelMapper.invokePersonnel(personnel.getPersonnelId(), USE_YES);
            return effect;

    }

    /**
     * 停用帐号
     */
    public int inactivePersonnel(Personnel personnel){
        int effect = personnelMapper.invokePersonnel(personnel.getPersonnelId(), USE_NO);
        return effect;
    }

    @Override
    public Personnel getByPersonnelId(int personnelId) {
        return this.personnelMapper.getByPersonnelId(personnelId);
    }

    @Override
    public Integer isExist(Personnel p) {
        return this.personnelMapper.isExist(p);
    }

}
